﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MyClock
{

    public delegate void Ringing(Clock clock);

    public class Clock : IDisposable
    {
        public DateTime Time { get; set; }
        public DateTime RingTime { get; set; }
        public bool IsRingOpen { get; set; }

        public event Ringing OnRinging;

        SoundPlayer player;

        public void Check()
        {
            if (IsRingOpen && Time == RingTime)
            {
                Console.WriteLine("时间到了");
                OnRinging(this);
                player = new SoundPlayer("ring.wav");
                player.Play();
            }
        }

        Thread t;

        public void TickTok()
        {
            t = new Thread(DoTickTok);
            t.Start();
        }

        void DoTickTok()
        {
            while (true)
            {
                Console.SetCursorPosition(0, 0);
                Time = Time.AddSeconds(1);
                Console.WriteLine(Time.ToString("yyyy-MM-dd HH:mm:ss"));
                Check();
                Console.SetCursorPosition(0, 1);
                Thread.Sleep(1000);
            }
        }

        public void Switch(bool isOn)
        {
            IsRingOpen = isOn;
            if (isOn == false && player != null)
            {
                player.Stop();
                player = null;
            }
        }

        public void Dispose()
        {
            Thread.Sleep(2000);
            Console.WriteLine("把闹钟砸了");
            //if(player!=null) player.Stop();
            player?.Stop();
            try
            {
                t?.Abort();
            }
            catch
            {
            }
        }
    }
}


/*
 闹钟
    -属性
    时间
    响铃时间
    闹铃开关
    +方法
    时间走动
    响铃
    调整开关(开/关)
 */